package com.example.springboot.controller;

import com.example.springboot.dto.PaymentDTO;
import com.example.springboot.entity.Payment;
import com.example.springboot.service.OrderService;
import com.example.springboot.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.RouteMatcher;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;

@RestController
@Api(tags = "支付接口")
@RequestMapping("/api/payments")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "创建支付", notes = "创建支付")
    @PostMapping("/pay")
    public ResponseEntity<?> completePayment(@RequestBody PaymentDTO paymentDTO) {
        if (paymentDTO.getOrderId() == null || paymentDTO.getUserId() == null || paymentDTO.getOrderAmount() == null) {
            return ResponseEntity.badRequest().body("订单ID、用户ID和支付金额不能为空");
        }

        try {
            // 根据订单类型进行不同的处理
            if ("self_service".equals(paymentDTO.getOrderType())) {
                // 自助洗衣的处理逻辑（原业务逻辑）
                // 查找支付记录
                Payment payment = paymentService.findPaymentByOrderIdAndUserIdAndType(
                        paymentDTO.getOrderId(),
                        paymentDTO.getUserId(),
                        paymentDTO.getOrderType()
                );


                if (payment == null) {
                    return ResponseEntity.badRequest().body("未找到支付记录或订单ID与用户ID不匹配");
                }

                // 校验支付金额（确保使用 BigDecimal 进行四舍五入到两位小数）
                BigDecimal orderAmount = paymentDTO.getOrderAmount().setScale(2, RoundingMode.HALF_UP);
                if (!compareAmounts(orderAmount, payment.getOrderAmount())) {
                    return ResponseEntity.badRequest().body("支付金额与订单金额不匹配");
                }

                // 自动完成支付
                paymentService.updatePaymentStatus(payment.getTransactionId(), "success");

                // 更新订单状态为 washing
                orderService.updateOrderStatusToWashing(payment.getTransactionId());

                return ResponseEntity.ok("支付成功，订单已开始洗涤");
            } else if ("merchant_service".equals(paymentDTO.getOrderType())) {
                // 商家服务的处理逻辑
                // 查找支付记录
                Payment payment = paymentService.findPaymentByOrderIdAndUserIdAndType(
                        paymentDTO.getOrderId(),
                        paymentDTO.getUserId(),
                        paymentDTO.getOrderType()
                );

                if (payment == null) {
                    return ResponseEntity.badRequest().body("未找到支付记录或订单ID与用户ID不匹配");
                }

                // 校验支付金额（确保使用 BigDecimal 进行四舍五入到两位小数）
                BigDecimal orderAmount = paymentDTO.getOrderAmount().setScale(2, RoundingMode.HALF_UP);
                if (!compareAmounts(orderAmount, payment.getOrderAmount())) {
                    return ResponseEntity.badRequest().body("支付金额与订单金额不匹配");
                }

                // 自动完成支付
                paymentService.updatePaymentStatus(payment.getTransactionId(), "success");

                // 更新商家服务订单的状态为上门中in_progress
                orderService.updateMOrderStatusToPickedUp(payment.getTransactionId());

                return ResponseEntity.ok("支付成功，商家上门中");
            } else {
                return ResponseEntity.badRequest().body("订单类型无效");
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body("支付失败: " + e.getMessage());
        }
    }

    // 使用 BigDecimal 比较金额并四舍五入到两位小数
    private boolean compareAmounts(BigDecimal amount1, BigDecimal amount2) {
        // 四舍五入到两位小数
        amount1 = amount1.setScale(2, RoundingMode.HALF_UP);
        amount2 = amount2.setScale(2, RoundingMode.HALF_UP);
        return amount1.compareTo(amount2) == 0; // 使用 compareTo 来比较 BigDecimal 对象
    }
}
